from common.utils.rights import permission_required, view_logging_required
from common.utils.file_read import file_read
from . import index_bp
from flask import render_template,request
from flask_wtf.form import CombinedMultiDict
from models.form import UploadForm
import cv2 as cv
import numpy as np


def imgMorphology(img, x, y, judge):  # x、y控制核的大小，judge=1开运算，judge=0闭运算
    kernel = np.ones((x, y), np.uint8)
    # 开运算：先腐蚀再膨胀
    if judge == 0:
        # 闭运算：先膨胀再腐蚀
        img_Operation = cv.morphologyEx(img, cv.MORPH_CLOSE, kernel)
        print('图像的闭运算 处理完毕')
        return img_Operation
    elif judge == 1:
        img_Operation = cv.morphologyEx(img, cv.MORPH_OPEN, kernel)
        print('图像的开运算 处理完毕')
        return img_Operation


@index_bp.get('/open_pro')
@index_bp.post('/open_pro')
@view_logging_required
@permission_required("open:pro")
def open_pro():
    if request.method == "GET":
        return render_template('admin/cv/open.html')
    else:
        form = UploadForm(CombinedMultiDict([request.form, request.files]))
        if form.validate():
            f = request.files['file']
            file_url = file_read(f)
            pic = cv.imread(file_url)
            judge = int(request.form.get('judge'))
            kernel_x = int(request.form.get('kx'))
            kernel_y = int(request.form.get('ky'))
            out_image = imgMorphology(pic, kernel_x, kernel_y,judge)
            res_pic = "static/download/open.jpg"
            cv.imwrite(res_pic, out_image)
            return render_template('admin/cv/open.html', pic=file_url, res_pic=res_pic)
        else:
            return "请传入正确的文件格式"